<script setup lang="ts">

definePageMeta({
  //布局
  layout: 'landing-layout',
  validate: async (route: any) => {
    return true
  }
})

interface DrawHistory {
  _id: string;
  user_id: string;
  prompt_id: string; //ComfyUI返回的任务ID
  params: ComfyUIProperties; //绘画参数
  options: ComfyUIOptions; //绘画选项
  status: 0 | 1; //是否完成，0未完成，1完成
  created_at: number;
  output: string[]; //输出图片地址
  is_deleted: boolean;
  is_public: boolean;
}

onMounted(async () => {
  await handleAdminGetData()
})

type DrawHistoryKeys = keyof DrawHistory;
// const tableHeaders: DrawHistoryKeys[] = ['output','created_at','is_deleted', 'is_public', 'params','_id', 'user_id', 'prompt_id', 'status']
const headers = [
  {
    title: 'select',
    align: 'start',
    sortable: false,
    key: 'select',
  },
  {
    title: 'output',
    align: 'start',
    sortable: false,
    key: 'output',
  },
  {
    title: 'created_at',
    align: 'start',
    key: 'created_at',
  },
  {
    title: 'is_deleted',
    align: 'start',
    key: 'is_deleted',
  },
  {
    title: 'is_public',
    align: 'start',
    key: 'is_public',
  },
  {
    title: 'params',
    align: 'start',
    key: 'params',
  },
  {
    title: '_id',
    align: 'start',
    key: '_id',
  },
  {
    title: 'user_id',
    align: 'start',
    key: 'user_id',
  },
  {
    title: 'prompt_id',
    align: 'start',
    key: 'prompt_id',
  },
  {
    title: 'status',
    align: 'start',
    key: 'status',
  },
]
const tableData = ref<DrawHistory[]>([])
const selected = ref<string[]>([])
watch(selected, (newValue, oldValue) => {
  console.log(newValue)
})

const handleAdminGetData = async () => {
  tableData.value = await Client_GET('/draw/history') as DrawHistory[]
}
/**
 * 修改图片的公开状态
 * @param id
 */
const handleHistoryPublicStatus = async (id: string) => {
  await Client_PATCH(`/draw/history/${id}`, {is_public: !tableData.value.find(item => item._id === id)?.is_public})
  //本地数据同步更新
  tableData.value = tableData.value.map(item => {
    if (item._id === id) {
      item.is_public = !item.is_public
    }
    return item
  })
  useSnackbarStore().showSuccessMessage(`${tableData.value.find(item => item._id === id)?.is_public ? '隐藏' : '公开'}成功`)
}
/**
 * 修改图片的删除状态
 */
const handleHistoryDeleteStatus = async (id: string) => {
  await Client_PATCH(`/draw/history/${id}`, {is_deleted: !tableData.value.find(item => item._id === id)?.is_deleted})
  //本地数据同步更新
  tableData.value = tableData.value.map(item => {
    if (item._id === id) {
      item.is_deleted = !item.is_deleted
    }
    return item
  })
  useSnackbarStore().showSuccessMessage(`${tableData.value.find(item => item._id === id)?.is_deleted ? '删除' : '恢复'}成功`)
}
/**
 * 删除单个历史记录by id
 * @param id
 */
const handleHistoryDeleteById = async (id: string) => {
  const res = await Client_DELETE('/draw/history/' + id)
}

const changeSelect = (id: string) => {
  if (selected.value.includes(id)) {
    selected.value = selected.value.filter(item => item !== id)
  } else {
    selected.value.push(id)
  }
}
const handleHistoryDeleteSelected = async () => {
  const promiselist = [] as Promise<void>[]
  for (const item of selected.value) {
    promiselist.push(handleHistoryDeleteById(item))
  }
  //一起提交，await
  await Promise.all(promiselist)
  //清空选择
  selected.value = []
  //同步更新本地表格数据
  await handleAdminGetData()
  useSnackbarStore().showSuccessMessage(`删除成功`)
}


// const handleAdminUpdateUserStatus = async (uid: string, status: 0 | 1|2) => {
//   //如果是管理员账户，不允许操作
//   if (tableData.value.find(item => item._id === uid)?.username.includes('admin')) {
//     useSnackbarStore().showErrorMessage('管理员账户不允许操作')
//     return
//   }
//   await Client_PATCH(`/users/${uid}`,{status})
//   useSnackbarStore().showSuccessMessage(`${status === 0 ? '启用' : '禁用'}成功`)
//   //同步更新本地表格数据
//   tableData.value = tableData.value.map(item => {
//     if (item._id === uid) {
//       item.status = status
//     }
//     return item
//   })
// }

</script>

<template>
  <!--  <v-table-->
  <!--      fixed-header-->
  <!--  >-->
  <!--    <thead>-->
  <!--    <tr>-->
  <!--      <th v-for="header in tableHeaders" class="text-left">-->
  <!--        {{ header.toUpperCase() }}-->
  <!--      </th>-->
  <!--    </tr>-->
  <!--    </thead>-->
  <!--    <tbody>-->
  <!--    <tr v-for="item in tableData">-->
  <!--      <td v-for="key in tableHeaders">-->
  <!--        <span v-if="key === 'created_at'">-->
  <!--          {{ new Date(item[key]).toLocaleString() }}-->
  <!--        </span>-->
  <!--        &lt;!&ndash;        显示用户状态 0 正常 1 禁用 3 删除&ndash;&gt;-->
  <!--        <span v-else-if="key === 'is_public'" class="d-flex align-center">-->
  <!--          <v-chip :color="item[key] ? 'green' : 'error'" size="small">{{item[key] ? '已公开' : '未公开'}}</v-chip>-->
  <!--          <v-btn  size="x-small" :color="item[key] ? 'warning' : 'green'" @click="handleHistoryPublicStatus(item._id)">{{item[key] ? '隐藏' : '公开'}}</v-btn>-->
  <!--        </span>-->
  <!--        <span v-else-if="key === 'is_deleted'" class="d-flex align-center">-->
  <!--          <v-chip :color="item[key] ? 'error' : 'green'" size="small">{{item[key] ? '已删除' : '正常'}}</v-chip>-->
  <!--          <v-btn  size="x-small" :color="item[key] ? 'green' : 'error'" @click="handleHistoryDeleteStatus(item._id)">{{item[key] ? '恢复' : '删除'}}</v-btn>-->
  <!--        </span>-->
  <!--        <span v-else-if="key === 'output'"><v-img :src="item[key]" width="100"/></span>-->
  <!--        <span v-else>-->
  <!--          {{ item[key] }}-->
  <!--        </span>-->
  <!--      </td>-->
  <!--    </tr>-->
  <!--    </tbody>-->
  <!--  </v-table>-->
  <!-- 删除记录按钮-->


  <v-data-table
      :headers="headers"
      :items="tableData"
      item-value="_id"
      density="compact"
      v-model="selected"
      item-key="_id"
      show-select
  >
    <template v-slot:top>
      <v-sheet class="ma-2 pa-2" elevation="2">
        <v-spacer></v-spacer>
        <v-btn size="small" color="error" @click="handleHistoryDeleteSelected()">批量删除</v-btn>
      </v-sheet>
    </template>
    <template v-slot:item="{ item }">
      <tr>
        <td></td>
        <td v-for="(headitem,index) in headers">
                      <span v-if="headitem.key === 'created_at'">
                        {{ new Date(item[headitem.key]).toLocaleString() }}
                      </span>
          <!--          选择-->
          <span v-else-if="headitem.key === 'select'">
                      <v-checkbox-btn v-if="headitem.key === 'select'"
                                      :model-value="selected.includes(item._id)"
                                      @click="changeSelect(item._id)"
                      ></v-checkbox-btn>
          </span>


          <!--        显示用户状态 0 正常 1 禁用 3 删除-->
          <span v-else-if="headitem.key === 'is_public'" class="d-flex align-center">
                        <v-chip :color="item[headitem.key] ? 'green' : 'error'"
                                size="small">{{ item[headitem.key] ? '已公开' : '未公开' }}</v-chip>
                        <v-btn size="x-small" :color="item[headitem.key] ? 'warning' : 'green'"
                               @click="handleHistoryPublicStatus(item._id)">{{
                            item[headitem.key] ? '隐藏' : '公开'
                          }}</v-btn>
                      </span>
          <span v-else-if="headitem.key === 'is_deleted'" class="d-flex align-center">
                        <v-chip :color="item[headitem.key] ? 'error' : 'green'"
                                size="small">{{ item[headitem.key] ? '已删除' : '正常' }}</v-chip>
                        <v-btn size="x-small" :color="item[headitem.key] ? 'green' : 'error'"
                               @click="handleHistoryDeleteStatus(item._id)">{{
                            item[headitem.key] ? '恢复' : '删除'
                          }}</v-btn>
                      </span>
          <span v-else-if="headitem.key === 'output'"><v-img v-for="(img,index) in item[headitem.key]" :src="img"
                                                             width="100"/></span>
          <span v-else>
                        {{ item[headitem.key] }}
                      </span>
        </td>

      </tr>
    </template>
  </v-data-table>
</template>

<style scoped lang="scss">

</style>